<template>
  <div class="container">
    <!-- 新增宠物 -->
    <div class="data-box" style="height: 540px;">
      <!-- 搜索框 -->
      <MySearch @parent-searchBtn="searchBtn"></MySearch>

      <div class="add" style="width:100px;height:40px; float: right; margin-bottom: -10px;">
        <el-button size="mini" type="primary" @click="handleAdd()" style="width: 80px">
          新增
        </el-button>
      </div>
      <!-- expand-row-keys为展开行的row-key数组，表格事件监听行展开状态去关闭其他行 -->
      <el-table 
        :data="tableData" 
        style="width: 100%" 
        :expand-row-keys="expandRowKeys" 
        row-key="petId"
        @expand-change="expandChange"  
        >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="宠物名称">
                <span>{{ props.row.petName }}</span>
              </el-form-item>
              <el-form-item label="宠物年龄">
                <span>{{ props.row.petAge }}</span>
              </el-form-item>
              <el-form-item label="宠物编号">
                <span>{{ props.row.petId }}</span>
              </el-form-item>
              <el-form-item label="宠物类型">
                <span>{{ props.row.petType }}</span>
              </el-form-item>
              <el-form-item label="宠物品种">
                <span>{{ props.row.petSpecies }}</span>
              </el-form-item>
              <el-form-item label="发布时间">
                <span>{{ props.row.pubDate | dateFormat }}</span>
              </el-form-item>
              <el-form-item label="已领养">
                <span>{{ props.row.isAdopt === 0 ? "否" : "是" }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="宠物编号" prop="petId"> </el-table-column>
        <el-table-column label="宠物名称" prop="petName"> </el-table-column>
        <el-table-column label="发布时间" prop="pubDate">
          <!-- 时间过滤器 -->
          <template slot-scope="scope">{{
            scope.row.pubDate | dateFormat
          }}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页按钮 -->
    <div class="pagination-box">
      <my-pagination
        style="text-align: right; margin-right: 100px"
        @parent-getData="getData"
        :dataCount="dataCount"
      ></my-pagination>
    </div>

    <!-- 编辑弹出框 -->
    <div class="container" style="display: inline-block">
      <!-- Form -->
      <el-dialog :title="editBoxTitle" :visible.sync="dialogFormVisible">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="宠物名称">
            <el-input v-model="formInline.petName"></el-input>
          </el-form-item>
          <el-form-item label="宠物品种">
            <el-input v-model="formInline.petSpecies"></el-input>
          </el-form-item>
          <el-form-item label="宠物类型">
            <el-input v-model="formInline.petType"></el-input>
          </el-form-item>
          <el-form-item label="宠物年龄">
            <el-input v-model="formInline.petAge"></el-input>
          </el-form-item>
          <el-form-item label="已被领养">
            <el-select v-model="formInline.isAdopt">
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancelBtn()">取 消</el-button>
          <el-button type="primary" @click="handleConfirmBtn()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 编辑弹出框多的end -->

  </div>
</template>
<script>
import MyDelMsgBox from "@/components/MyDelMsgBox.vue";
import MyPagination from "@/components/MyPagination.vue";
import MySearch from "@/components/MySearch.vue";

export default {
  components: { MyDelMsgBox, MyPagination, MySearch },
  data() {
    return {
      pageNum: 1,
      tableData: [], // 页面展示的数据
      dataCount: 0,  // 获取数据总条数
      dialogFormVisible: false, //编辑框弹出标志
      formInline: {   // 编辑框数据绑定
        petId: 0,
        petName: "",
        petSpecies: "",
        petType: "",
        petAge: '',
        isAdopt: '',
      },
      expandRowKeys: [], // 展开行row-key的数组
      editBoxTitle: '修改宠物信息',  // 编辑框的标题
      input: ''
    };
  },
  mounted() {
    this.getData(this.pageNum, 5);
    this.getDataCount();
  },
  methods: {
    // 根据页码发起请求获取数据
    getData(pageNum, pageSize) {
      // 分页组件调用此方法时，更新当前页码
      this.pageNum = pageNum;
      this.$axios
        .get(`pet/getByPage?pageNum=${pageNum}&pageSize=${pageSize}`)
        .then((result) => {
          // console.log(result.data)
          this.tableData = result.data;
        })
        .catch((err) => {
          console.error(err)
        });
    },
    // 获取数据的总条数
    getDataCount() {
      this.$axios
        .get("pet/getDataCount")
        .then((result) => {
          this.dataCount = result.data;
        })
        .catch((err) => {
          alert(err);
        });
    },
    // 响应按钮事件处理函数
    handleAdd(){
      this.editBoxTitle = '添加宠物'
      this.dialogFormVisible = true
    },
    handleEdit(data) {
      this.editBoxTitle = '修改宠物信息'
      this.dialogFormVisible = true;
      this.initFormInline(data);
    },
    handleDelete(index, itemData) {
      // this.$refs.mydelmsgbox.open();
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        // 执行删除
        this.onDelData(itemData.petId);
      }).then(() => {
        this.tableData.splice(index, 1)
        this.getData(this.pageNum, 5)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
      
    },
    // 发起请求添加数据
    onAddData(){
      this.$axios.post("pet/insertPet", {
        petName: this.formInline.petName,
        petSpecies: this.formInline.petSpecies,
        petType: this.formInline.petType,
        petAge: this.formInline.petAge,
        isAdopt: this.formInline.isAdopt,
      }).then((result) => {
        if (result.data == 1) {
            this.dialogFormVisible = false;
            // 添加数据后刷新数据
            this.getData(this.pageNum, 5);
            this.getDataCount()
            this.$message({
              showClose: true,
              message: "添加成功！",
              type: "success",
            });
        }
        this.formInline = {}
      }).catch((err) => {
        alert(err)
      });
    },
    // 发起请求删除数据
    onDelData(petId){
      this.$axios.get("pet/deletePetById?petId=" + petId)
      .then((result) => {
        if(result.data == 1){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        } else {
          this.$message({
            showClose: true,
            message: '删除失败',
            type: 'warning'
          });
        }
      }).catch((err) => {
        this.$message({
            showClose: true,
            message: '错误信息：' + err,
            type: 'warning'
        });
      });
    },
    // 发起更改宠物信息的post请求
    onUpdate() {
      this.$axios
        .post("pet/updateByPetId", {
          petId: this.formInline.petId,
          petName: this.formInline.petName,
          petSpecies: this.formInline.petSpecies,
          petType: this.formInline.petType,
          petAge: this.formInline.petAge,
          isAdopt: this.formInline.isAdopt,
        })
        .then((result) => {
          if (result.data == 1) {
            this.dialogFormVisible = false;
            // 编辑数据后刷新数据
            this.getData(this.pageNum, 5);
          }
        })
        .then(() => {
          this.$message({
            showClose: true,
            message: "更新成功！",
            type: "success",
          });
        })
        .catch((err) => {
          alert(err);
        });
    },
    handleCancelBtn(){
      this.dialogFormVisible = false
      this.formInline = {}
    },
    handleConfirmBtn(){
      if(this.editBoxTitle == '修改宠物信息'){
        this.onUpdate()
      } else {
        this.onAddData()
      }
    },
    // 初始化弹出框的placeholder
    initFormInline(newData) {
      let newForm = {
        petId: newData.petId,
        petName: newData.petName,
        petSpecies: newData.petSpecies,
        petType: newData.petType,
        petAge: newData.petAge,
        isAdopt: newData.isAdopt,
      };
      this.formInline = newForm;
    },
    expandChange(row){
      if(this.expandRowKeys.length == 0) {
        this.expandRowKeys.push(row.petId)
      } else if(this.expandRowKeys.length == 1 && this.expandRowKeys[0] != row.petId) {
        this.expandRowKeys = []
        this.expandRowKeys.push(row.petId)
      } else {
        this.expandRowKeys = []
      }
    },
    searchBtn(value){
      if(value != ''){
        let newTable = this.tableData.filter(
          item => item.petName.toLowerCase().includes(value.toLowerCase())
        )
        this.tableData = newTable;
      } else {
        this.getData(this.pageNum, 5)
      }
    }
  },
};
</script>
<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 30%;
}
.demo-form-inline {
  padding: 0px 20px;
}
.el-input,
.el-select {
  width: 250px;
}
</style>